<template>
  <div class="os-main">
    <ConfigForm v-model="dataForm" :config="config" ref="configFormRef" />

    <el-button type="primary" @click="openJson">查看表单数据</el-button>

    <el-drawer v-model="drawerVisiable" title="数据视图" :direction="'rtl'" size="40%">
      <CodeView :code-json="JSON.stringify(dataForm, null, '\t')"></CodeView>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import type { Config } from '@/components/ConfigForm'
import PopupSelect from '@/components/PopupSelect/index.vue'
import { getTableData } from '@/api/index'
import { ref, markRaw } from 'vue';
import CodeView from '@/components/CodeView/index.vue'
import ConfigForm from '@/components/ConfigForm/index'

const queryData = { pageSize: 5, pageNum: 1 }
const tableColumns = [
  { prop: 'name', label: '姓名', minWidth: '200' },
  { prop: 'sex', label: '性别', align: 'center' },
  { prop: 'age', label: '年龄', align: 'center' }
]
const tableSearchList = [
  { prop: 'name', label: '姓名' },
  { prop: 'sex', label: '性别', options: [{ label: '男', value: '1' }, { label: '女', value: '2' }] },
]

/**ConfigForm绑定对象 */
const dataForm = ref<ObjectAny>({
  demo2: [{ name: '张三', id: '3' }]
})

/**ConfigForm配置 */
const config = ref<Config>({
  mode: 'add',
  formProps: {},
  rowProps: {},
  columns: [
    // 除了实现部分比较复杂的element-plus表单组件外，还可以用来做一些复合的内容
    {
      prop: 'demo1', label: '自定义的弹框选择器', type: 'custom', is: markRaw(PopupSelect),
      props: { queryMethod: getTableData, queryData, tableColumns },
      value: { name: '张三', id: '3' }, // 如果dataForm有指定值，等同于{ name: dataForm.value.demo1Name, id: dataForm.value.demo1Id }
      events: {
        'update:modelValue': (data?: ObjectAny) => {
          if (data) {
            dataForm.value.demo1 = { name: data.name, id: data.id }
          } else {
            dataForm.value.demo1 = ''
          }
        }
      }
    },
    {
      prop: 'demo2', label: '自定义的弹框选择器(多选)', type: 'custom', is: markRaw(PopupSelect),
      props: { multiple: true, queryMethod: getTableData, queryData, tableColumns, tableSearchList },
      events: {
        'update:modelValue': (data: ObjectAny[]) => {
          if (data.length) {
            dataForm.value.demo2 = data.map(item => {
              if (!item.id) return item
              return { name: item.name, id: item.id }
            })
          } else {
            dataForm.value.demo2 = ''
          }
        }
      }
    },
  ]
})

// 数据视图
const drawerVisiable = ref(false)
const openJson = () => {
  drawerVisiable.value = true
}
</script>